package com.cbs.android.module.user.user.module.setinformation;

import android.graphics.Bitmap;

import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.log.L;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.cbs.android.module.user.user.module.UserModuleSetInformation;
import com.cbs.component.android.storage.storageinterface.StorageHandler;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.util.Hashtable;

/**
 * Created by broche on 2/27/16.
 */
public class UserModuleSetUserAvatar {
    private static final String TAG = UserModuleSetUserAvatar.class.getName();
    private Bitmap bitmap;
    private ModuleHandler<User> moduleHandler;
    private UserModuleSetInformation setInformation = null;

    public UserModuleSetUserAvatar(Bitmap bitmap, ModuleHandler<User> moduleHandler) {
        this.bitmap = bitmap;
        this.moduleHandler = moduleHandler;
    }

    public void start() {
        if (UserModule.getUser() == null) {
            if (moduleHandler != null) {
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setErrorNo(99999);
                errorResponse.setErrorMsg("请先登录您的账号");
                moduleHandler.onFailure(999, new Gson().toJson(errorResponse));
            }
            return;
        }
        User user = UserModule.getUser();
        Hashtable<String, String> params = new Hashtable<>();
        params.put("userid", user.getId() + "");
        params.put("token", user.getToken());
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        UserModule.getStorageService().upload("user_avatar_" + user.getId() + "_" + System.currentTimeMillis(), "user", "avatar", params, byteArray, new StorageHandler() {
            @Override
            public void onSuccess(String id, String key, String result) {
                User user = new User();
                user.setAvatar(key);
                setInformation = new UserModuleSetInformation(user, moduleHandler);
                setInformation.start();
            }

            @Override
            public void onException(String id, String key, Exception e) {
                if (moduleHandler != null) {
                    moduleHandler.onException(e);
                }
            }

            @Override
            public void onProgress(String id, String key, double percent) {
                L.d(TAG, "progress: " + percent);
            }
        });
    }
}
